package top.cardone.consumer

import groovy.util.logging.Log4j2
import org.springframework.beans.BeansException
import org.springframework.beans.factory.InitializingBean
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.core.io.Resource
import top.cardone.context.ApplicationContextHolder

@Log4j2
class JavaConfig implements ApplicationContextAware, InitializingBean {
    @Override
    void afterPropertiesSet() throws Exception {
        log.warn(ApplicationContextHolder.applicationContext.getEnvironment().getProperty("spring.application.name") + " start: " + ApplicationContextHolder.applicationContext.getEnvironment().getProperty("spring.profiles.active"))

        String[] groovyScriptEngineUrls = ApplicationContextHolder.applicationContext.getEnvironment().getProperty("top.cardone.context.ApplicationContextHolder.groovyScriptEngineUrls")?.split(",")

        if (groovyScriptEngineUrls) {
            for (int i = 0; i < groovyScriptEngineUrls.length; i++) {
                Resource resource = ApplicationContextHolder.applicationContext.getResource(groovyScriptEngineUrls[i])

                if (!resource.exists()) {
                    continue
                }

                groovyScriptEngineUrls[i] = resource.getFile().getAbsolutePath()
            }

            ApplicationContextHolder.groovyScriptEngine = new GroovyScriptEngine(groovyScriptEngineUrls)
        }
    }

    @Override
    void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextHolder.applicationContext = applicationContext
    }
}